package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.core.cache.TeamMetaLocalCache;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Team;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.system.domain.AdminTeam;
import com.ruoyi.common.core.domain.entity.TeamMeta;
import com.ruoyi.system.mapper.ISysTeamMapper;
import com.ruoyi.system.service.ISysTeamService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author : hcl
 * @Date : 2023/8/2
 */
@Service
public class ISysTeamServiceImpl implements ISysTeamService {
    @Resource
    private ISysTeamMapper teamMapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public Team selectTeamById(Long teamId, Long userId) {
        String key = "HS_TM_" + teamId + "_" + userId;
        Boolean has = (Boolean) redisCache.getCacheObject(key);
        if (Objects.nonNull(has) && has) {
            return redisCache.getCacheObject("TM_" + teamId);
        }
        if (has == null) {
            List<Team> teams = teamMapper.selectUserTeam(teamId, userId);
            if (CollectionUtils.isNotEmpty(teams)) {
                redisCache.setCacheObject(key, true, 10, TimeUnit.MINUTES);
                redisCache.setCacheObject("TM_" + teamId, teams.get(0), 10, TimeUnit.MINUTES);
                return teams.get(0);
            }
            redisCache.setCacheObject(key, false, 10, TimeUnit.MINUTES);
        }
        return null;
    }

    @Transactional
    @Override
    public void createTeam(Team team, Long creator) {
        if (!NumberUtils.isTrue(team.getId())) {
            team.setCreator(creator);
            teamMapper.addTeam(team);
            joinTeam(team.getId(), creator);
        }
    }

    @Transactional
    @Override
    public void joinTeam(Long teamId, Long adminId) {
        List<Team> teams = selectTeamByUserId(adminId);
        if (!CollectionUtils.isEmpty(teams)) {
            List<Long> teamIds = teams.stream().map(Team::getId).collect(Collectors.toList());
            if (teamIds.contains(teamId)) return;
        }
        AdminTeam adminTeam = new AdminTeam();
        adminTeam.setTeamId(teamId);
        adminTeam.setAdminId(adminId);
        teamMapper.addAdminTeam(adminTeam);
    }

    @Override
    public List<Team> selectTeamByUserId(Long userId) {
        if (NumberUtils.isTrue(userId)) {
            return teamMapper.selectUserTeam(null, userId);
        }
        return Collections.emptyList();
    }

    @Transactional
    @Override
    public void updateTeamMeta(TeamMeta meta) {

    }

    /**
     * 新创建的应用校验是否需要添加teamMeta
     */
    @Override
    public AjaxResult meta(HttpServletRequest request, Team team) {
        Meta meta = selectTeamMeta(team.getId());
        if (meta == null) {
            return AjaxResult.success()
                    .data("type", team.getTeamType())
                    .data("teamId", team.getId())
                    .data("needConfig", true);
        }
        return AjaxResult.success().data("teamId", team.getId());
    }

    @Override
    public Meta selectTeamMeta(Long teamId) {
        Meta meta = TeamMetaLocalCache.findMeta(teamId);
        if (meta == null) {
            List<TeamMeta> teamMetas = teamMapper.teamMeta(teamId);
            if (!CollectionUtils.isEmpty(teamMetas)) {
                Map<String, String> metaMap = teamMetas.stream()
                        .collect(Collectors.toMap(TeamMeta::getName, TeamMeta::getValue));
                meta = Meta.of(metaMap, teamId);
                TeamMetaLocalCache.putMeta(teamId, meta);
            }
        }
        return meta;
    }
}
